<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:orders:edit']"
        >修改订单</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="!ids.length"
          @click="handleDistribute"
          v-hasPermi="['system:orders:status']"
        >配货完成</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-truck"
          size="mini"
          :disabled="!ids.length"
          @click="handleShip"
          v-hasPermi="['system:orders:status']"
        >出库</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="!ids.length"
          @click="handleClose"
          v-hasPermi="['system:orders:status']"
        >关闭订单</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="订单总价" align="center" prop="orderPrice" />
      <el-table-column label="订单状态" align="center" prop="status.statusName" />
      <el-table-column label="订单支付方式" align="center" prop="orderPayment" />
      <el-table-column label="收货地址" align="center" prop="orderAddress" />
      <el-table-column label="添加时间" align="center" prop="orderAddtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderAddtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" @click="showOrderDetail(scope.row)">查看订单详情</el-button>
          <el-button type="text" @click="showConsignee(scope.row)">查看收件人信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="订单详情" :visible.sync="centerDialogVisible_order" width="30%" center>
      <el-table :data="orderProducts">
        <el-table-column prop="product.productName" label="商品名称"/>
        <el-table-column prop="product.productSaleprice" label="售价"/>
        <el-table-column prop="orderProductProductNum" label="数量"/>
      </el-table>
    </el-dialog>
    <el-dialog title="收件人信息" :visible.sync="centerDialogVisible_consignee" width="30%" center>
      <div style="padding: 20px">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="收货地址">
            {{ currentConsigneeAddress || '暂无地址信息' }} <!-- 确保绑定变量正确 -->
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单总价" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单总价" />
        </el-form-item>
        <el-form-item label="收货地址" prop="orderAddress">
          <el-input v-model="form.orderAddress" placeholder="请输入收货地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders, getOrderProducts } from "@/api/system/orders"

export default {
  name: "Orders",
  data() {
    return {
      orderProducts: [],
      currentOrder: null,
      currentConsigneeAddress: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      centerDialogVisible_order: false,
      centerDialogVisible_consignee: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    showConsignee(row) {
      this.currentConsigneeAddress = row.orderAddress
      this.centerDialogVisible_consignee = true
    },
    async showOrderDetail(row) {
      this.currentOrder = row;
      try {
        const res = await getOrderProducts(row.orderId);
        this.orderProducts = res.data;
        this.centerDialogVisible_order = true;
      } catch (error) {
        this.$modal.msgError("获取订单商品失败");
      }
    },
    // 新增方法 - 配货完成
    handleDistribute() {
      this.checkStatus(2, 3, '只有已支付状态的订单可以进行配货操作');
    },
    // 新增方法 - 出库
    handleShip() {
      this.checkStatus([2,3], 4, '只有已支付或配货完成的订单可以执行出库操作');
    },
    // 新增方法 - 关闭订单
    handleClose() {
      this.checkStatus([1,2,3,4], 6, '当前订单状态不可关闭');
    },
    // 通用状态检查方法
    checkStatus(validStatus, targetStatus, errorMsg) {
      if (!this.ids.length) {
        this.$modal.msgWarning("请至少选择一条订单")
        return false // 增加返回值控制流程
      }
      if (this.ids.length !== 1) {
        this.$modal.msgWarning("请选择一条订单进行操作");
        return;
      }
      const order = this.ordersList.find(item => item.orderId === this.ids[0]);
      const isValid = Array.isArray(validStatus) ?
        validStatus.includes(order.orderStatusId) :
        order.orderStatusId === validStatus;

      if (!isValid) {
        this.$modal.msgWarning(errorMsg);
        return;
      }

      this.$modal.confirm(`确认要执行此操作吗？`).then(() => {
        this.updateStatus(order.orderId, targetStatus);
      });
    },
    // 更新状态方法
    updateStatus(orderId, status) {
      const data = { orderId: orderId, orderStatusId: status } // 组装参数对象
      this.loading = true
      updateOrders(data).finally(() => { // 调用API接口
        this.loading = false
        this.getList() // 刷新列表
      })
    },
    /** 查询订单管理列表 */
    getList() {
      this.loading = true
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加订单管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (this.ids.length > 1) {
        this.$modal.msgWarning("请选择一条订单进行修改");
        return;
      }
      const orderId = row?.orderId || this.ids[0];
      getOrders(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
  }
}
</script>
